package cn.itzzx.lagou.netty.rpc;

import cn.itzzx.lagou.netty.rpc.common.service.UserService;
import cn.itzzx.lagou.netty.rpc.common.util.ServerLoadBalancerUtil;
import cn.itzzx.lagou.netty.rpc.customer.RPCConsumer;
import io.netty.util.internal.StringUtil;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.*;
import java.util.stream.Collectors;

/**
 * TODO 写点注视啦
 *
 * @author Martin
 * @date 2020-06-17
 * @see 1.0
 */
public class ConsumerBoot {

    /**
     * 提供者信息
     * key == host:port & delay
     * value == UserService
     */
    private static Map<String, UserService> servers = new HashMap<String, UserService>();

    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        //连接服务端，从zookeeper获取连接信息
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("10.211.55.7:2181")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(retryPolicy)
                .build();
        client.start();
        List<String> nodes = client.getChildren().forPath("/task-01");
        for (String node : nodes) {
            //127.0.0.1:8089
            String[] split = node.split(":");
            UserService service = (UserService) RPCConsumer.createProxy(UserService.class, split[0], Integer.parseInt(split[1]));
            //获取延迟时间
            Stat stat = client.checkExists().forPath("/delay/" + node);
            if (stat == null) {
                //默认设置0延迟
                Random random = new Random();
                //随机0～1000 毫秒
                String delay = String.valueOf(random.nextInt(1000) % (1000 + 1));
                client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/delay/" + node, delay.getBytes());
            }
            servers.put(node, service);
        }
        //监听task-01
        listenerServer(client, "/task-01");

        while (true) {
            if (servers.size() < 1) {
                continue;
            }
            UserService userService = ServerLoadBalancerUtil.selectBalanceService(servers, client);
            try {
                String result = userService.sayHello("are you ok !!");
                System.out.println("收到服务端信息: " + result);
            } catch (Exception e) {
                e.getMessage();
            }
            Thread.sleep(2000);
        }
    }


    /**
     * 监听
     *
     * @param client
     * @param path
     * @throws Exception
     */
    public static void listenerServer(CuratorFramework client, String path) throws Exception {
        PathChildrenCache cache = new PathChildrenCache(client, path, true);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                ChildData eventData = pathChildrenCacheEvent.getData();
                switch (pathChildrenCacheEvent.getType()) {
                    case CHILD_ADDED:
                        String content = new String((client.getData().forPath(eventData.getPath())), "UTF-8");
                        if (!(content == null || "".equals(content))) {
                            String[] split = content.split(":");
                            UserService service = (UserService) RPCConsumer.createProxy(UserService.class, split[0], Integer.parseInt(split[1]));
                            System.out.println("[" + eventData.getPath() + "]节点添加");

                            //获取延迟时间
                            Stat stat = client.checkExists().forPath("/delay/" + content);
                            if (stat == null) {
                                Random random = new Random();
                                //随机0～1000 毫秒
                                String delay = String.valueOf(random.nextInt(1000) % (1000 + 1));
                                client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/delay/" + content, delay.getBytes());
                            }
                            servers.put(content, service);
                        }
                        break;
                    case CHILD_REMOVED:
                        System.out.println("[" + eventData.getPath() + "]节点删除");
                        String serviceId = new String((client.getData().forPath(eventData.getPath())), "UTF-8");
                        servers.remove(serviceId);
                        break;
                    default:
                        break;
                }
            }
        });
        cache.start();

    }
}
